package com.wstuo.common.scheduledTask.utils;

import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.expression.ParseException;

import com.wstuo.common.util.TimeUtils;


/**
 * 简单的任务管理类
 * @author WSTUO
 *
 */
public class QuartzManager {
	   private  SchedulerFactory sf = new StdSchedulerFactory();
	   private  String JOB_GROUP_NAME = "group1";
	   private  String TRIGGER_GROUP_NAME = "trigger1";
	   private static final Logger LOGGER = Logger.getLogger(QuartzManager.class);  
	   /** *//**
	    * 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
	    * @param jobName 任务名
	    * @param job     任务
	    * @param time    时间设置，参考quartz说明文档
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	   public void addJob(String jobName,Job job,String time)
	                               throws SchedulerException, ParseException{
	       Scheduler sched = sf.getScheduler();
	       JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, job.getClass());//任务名，任务组，任务执行类
	       //触发器
	       CronTrigger trigger =
	            new CronTrigger(jobName, TRIGGER_GROUP_NAME);//触发器名,触发器组
	       try {
	    	   
	    	   trigger.setCronExpression(time);
	       } catch (java.text.ParseException e) {
				LOGGER.error(e);
	       }
	       trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
	       //触发器时间设定
	       sched.scheduleJob(jobDetail,trigger);
	       //启动
	       if(!sched.isShutdown())
	          sched.start();
	   }
	  
	   /** 
	    * 添加一个定时任务
	    * @param jobName 任务名
	    * @param jobGroupName 任务组名
	    * @param triggerName 触发器名
	    * @param triggerGroupName 触发器组名
	    * @param job     任务
	    * @param time    时间设置，参考quartz说明文档
	    * @param startTime 日计划的开始时间
	    * @param obj JOB参数对像
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	   public void addJob(String jobName,String jobGroupName,
	                             String triggerName,String triggerGroupName,
	                             Job job,String time,Date startTime,Date endTime,Object obj,Long reportId)
	                               throws SchedulerException,ParseException{
	       Scheduler sched = sf.getScheduler();
	       JobDetail jobDetail = new JobDetail(jobName, jobGroupName,job.getClass(),false,false,true);//任务名，任务组，任务执行类
	       if(jobDetail!=null){
	       
		       jobDetail.getJobDataMap().put("parameter", obj);
		       jobDetail.getJobDataMap().put("reportId", reportId);
	       }
	       
	       
	       //触发器
	       CronTrigger trigger =
	            new CronTrigger(triggerName, triggerGroupName);//触发器名,触发器组
	       try {
	    	   if(startTime!=null){
	    		   startTime = TimeUtils.dateFormat(startTime, TimeUtils.DATE_PATTERN);
	    	   }
	    	   //任务开始时间//默认为当前时间
	    	   if(startTime!=null && startTime.getTime()-new Date().getTime()>0){
	    		   trigger.setStartTime(startTime);
	    	   }else{
	    		   trigger.setStartTime(new Date());
	    	   }
	    	   if(endTime!=null){
	    		   trigger.setEndTime(endTime);
	    	   }  
	    	   trigger.setCronExpression(time);
	    	   trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
	    	   sched.scheduleJob(jobDetail,trigger);
	    	   if(!sched.isShutdown())
			          sched.start();
	       } catch (java.text.ParseException e) {
	    	   LOGGER.error("任务调度出现异常!",e);
	       }//触发器时间设定
	       
	   }
	   /** 
	    * 添加一个定时任务
	    * @param jobName 任务名
	    * @param jobGroupName 任务组名
	    * @param triggerName 触发器名
	    * @param triggerGroupName 触发器组名
	    * @param job     任务
	    * @param time    时间设置，参考quartz说明文档
	    * @param obj JOB参数对像
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	   public void addJob1(String jobName,String jobGroupName,
               String triggerName,String triggerGroupName,
               Job job,String time,Object obj,Long reportId)
                 throws SchedulerException, ParseException{
			Scheduler sched = sf.getScheduler();
			JobDetail jobDetail = new JobDetail(jobName, jobGroupName, job.getClass());//任务名，任务组，任务执行类
			if(jobDetail!=null){
				jobDetail.getJobDataMap().put("parameter", obj);
				jobDetail.getJobDataMap().put("reportId", reportId);
			}
			//触发器
			CronTrigger trigger =
			new CronTrigger(triggerName, triggerGroupName);//触发器名,触发器组
			try {
				trigger.setCronExpression(time);
			} catch (java.text.ParseException e) {
				LOGGER.error(e);
			}//触发器时间设定
			trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
			sched.scheduleJob(jobDetail,trigger);
			if(!sched.isShutdown())
			sched.start();
		}
	   
	   
	   /**
	    * 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
	    * @param jobName
	    * @param time
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	   public void modifyJobTime(String jobName,String time)
	                                  throws SchedulerException, ParseException{
	       Scheduler sched = sf.getScheduler();
	       Trigger trigger = sched.getTrigger(jobName,TRIGGER_GROUP_NAME);
	       if(trigger != null){
	           CronTrigger ct = (CronTrigger)trigger;
	           try {
	        	   ct.setCronExpression(time);
	           } catch (java.text.ParseException e) {
	        	   LOGGER.error(e);
	           }
	           sched.resumeTrigger(jobName,TRIGGER_GROUP_NAME);
	       }
	   }
	  
	   /**
	    * 修改一个任务的触发时间
	    * @param triggerName
	    * @param triggerGroupName
	    * @param time
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	   public void modifyJobTime(String triggerName,String triggerGroupName,
	                                    String time)
	                                  throws SchedulerException, ParseException{
	       Scheduler sched = sf.getScheduler();
	       
	       Trigger trigger = sched.getTrigger(triggerName,triggerGroupName);
	       
	       if(trigger != null){
	           CronTrigger ct = (CronTrigger)trigger;
	           //修改时间
	           try {
	        	   
	        	   ct.setCronExpression(time);
				} catch (java.text.ParseException e) {
					LOGGER.error(e);
				}
	           //重启触发器
	           sched.resumeTrigger(triggerName,triggerGroupName);
	       }
	   }
	  
	   /**
	    * 从Scheduler 移除当前的Job,修改Trigger  
	    * @param jobName
	    * @param jobGroupName
	    * @param triggerName
	    * @param triggerGroupName
	    * @param time
	    * @param startTime
	    * @param endTime
	    * @param obj
	    * @param reportId
	    * @throws SchedulerException
	    * @throws ParseException
	    */
	    public void modifyJobTime(String jobName,String jobGroupName,String triggerName,String triggerGroupName,String time,Date startTime,Date endTime,Object obj,Long reportId)
	    	throws SchedulerException, ParseException{  
	        Scheduler sched = sf.getScheduler();  
	        JobDetail jobDetail =sched.getJobDetail(jobName, jobGroupName);//任务名，任务组，任务执行类'
	        if(jobDetail!=null){
		        jobDetail.getJobDataMap().put("parameter", obj);
		        jobDetail.getJobDataMap().put("reportId", reportId);
	        }
	       
	        Trigger trigger =sched.getTrigger(triggerName,triggerGroupName);  
	        if  (trigger !=null ) {  
	            CronTrigger ct = (CronTrigger) trigger;  
	            // 移除当前进程的Job   
	            sched.deleteJob(jobDetail.getName(), jobDetail.getGroup());  
	            // 修改Trigger   
	            try {
	            	//任务开始时间//默认为当前时间
	 	    	   if(startTime!=null && startTime.getTime()-new Date().getTime()>0){
	 	    		  ct.setStartTime(startTime);
	 	    	   }else{
	 	    		  ct.setStartTime(new Date());
	 	    	   }
	 	    	   if(endTime!=null)
	 	    		  ct.setEndTime(endTime);
	 	    	   
	 	    	   ct.setCronExpression(time);
				} catch (java.text.ParseException e) {
					LOGGER.error(e);
				}
	            // 重新调度jobDetail  
				ct.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
	            sched.scheduleJob(jobDetail, ct);  
	        }  
	    }   
	   
	   
	   /**
	    * 移除一个任务(使用默认的任务组名，触发器名，触发器组名)
	    * @param jobName
	    * @throws SchedulerException
	    */
	   public void removeJob(String jobName)
	                               throws SchedulerException{
	       Scheduler sched = sf.getScheduler();
	       sched.pauseTrigger(jobName,TRIGGER_GROUP_NAME);//停止触发器
	       sched.unscheduleJob(jobName,TRIGGER_GROUP_NAME);//移除触发器
	       sched.deleteJob(jobName,JOB_GROUP_NAME);//删除任务
	   }
	  
	   /**
	    * 移除一个任务
	    * @param jobName
	    * @param jobGroupName
	    * @param triggerName
	    * @param triggerGroupName
	    * @throws SchedulerException
	    */
	   public void removeJob(String jobName,String jobGroupName,
	                                String triggerName,String triggerGroupName)
	                               throws SchedulerException{
	       Scheduler sched = sf.getScheduler();
	       sched.pauseTrigger(triggerName,triggerGroupName);//停止触发器
	       sched.unscheduleJob(triggerName,triggerGroupName);//移除触发器
	       sched.deleteJob(jobName,jobGroupName);//删除任务
	   }
}
